package com.ruoyi.meiyijia.service.impl;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.file.parsing.excel.ExcelParsingUtil;
import com.ruoyi.meiyijia.entity.FileMeiyijiaInventory;
import com.ruoyi.meiyijia.mapper.FileMeiyijiaInventoryMapper;
import com.ruoyi.meiyijia.service.FileMeiyijiaInventoryService;
import com.ruoyi.meiyijia.vo.DictTreeVo;
import com.ruoyi.meiyijia.vo.FileMeiyijiaInventoryListSumVo;
import com.ruoyi.meiyijia.vo.FileMeiyijiaInventoryListVo;
import com.ruoyi.meiyijia.vo.FileMeiyijiaInventoryParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: TheRaging
 * @date: 2023年05月18日 09:04:00
 * @description:
 */
@Service
@Slf4j
@DataSource(DataSourceType.MYJ)
public class FileMeiyijiaInventoryServiceImpl implements FileMeiyijiaInventoryService {

    private final BigDecimal hundred = new BigDecimal("100");

    /**
     * 导入文件的批量插入的接口
     *
     * @param inputStream
     */

    @Autowired
    private ExcelParsingUtil<FileMeiyijiaInventory> excelParsingUtil;

    @Resource
    private FileMeiyijiaInventoryMapper fileMeiyijiaInventoryMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importExcel(MultipartFile file) {
        String filePath = file.getOriginalFilename();

        InputStream fis = null;
        try {
            fis = file.getInputStream();
            Workbook workbook = null;
            if (filePath.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (filePath.endsWith(".xls") || filePath.endsWith(".et")) {
                workbook = new HSSFWorkbook(fis);
            }

            fis.close();

            // 获取第一个sheet表，也可使用sheet表名获取
            Sheet sheet = workbook.getSheetAt(0);
            LocalDateTime dateTime = LocalDateTime.now();
            /**
             * 生成唯一标识
             */
            StringBuffer str = new StringBuffer();
            str.append(dateTime.getYear());
            str.append(dateTime.getMonthValue() < 10 ? "0" + dateTime.getMonthValue() : dateTime.getMonthValue());
            str.append(dateTime.getDayOfMonth() < 10 ? "0" + dateTime.getDayOfMonth() : dateTime.getDayOfMonth());
            Random r = new Random();
            int s = r.nextInt(1000000000);
            if (s < 0) {
                s = 0 - s;
            }
            str.append(s);
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/M/d H:m:s");
            List<FileMeiyijiaInventory> list = excelParsingUtil.getSheetByIndex(FileMeiyijiaInventory.class, sheet, (val, i, item) -> {
                switch (i) {
                    case 0:
                        item.setBigType(val);
                        break;
                    case 1:
                        item.setType(val);
                        break;
                    case 2:
                        // System.out.println("第二列跳过-----------");
                        break;
                    case 3:
                        item.setCode(val);
                        break;
                    case 4:
                        item.setBarCode(val);
                        break;
                    case 5:
                        item.setNameSpecification(val);
                        break;
                    case 6:
                        item.setUnit(val);
                        break;
                    case 7:
                        item.setWholesalePrice(val);
                        break;
                    case 8:
                        item.setMsrpPrice(val);
                        break;
                    case 9:
                        item.setRetailPrive(val);
                        break;
                    case 10:
                        item.setCount(val);
                        break;
                    case 11:
                        item.setQualityTerm(val);
                        break;
                    case 12:
                        item.setWarehousingTime(LocalDateTime.parse(val, df));
                        break;
                }
                /**
                 * 设置批次值
                 */
                return item;
            }, item -> {
                item.setCrtTime(dateTime);
                item.setId(str.toString());
            });

            /**
             * 批量插入数据库
             */
            int count = fileMeiyijiaInventoryMapper.insertbatch(list);
            if (count != list.size()) {
                throw new Exception("库存数据入库失败！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }


    /**
     * 查询美宜佳现有库存列表
     *
     * @param fileMeiyijiaInventoryParam 美宜佳现有库存
     * @return 美宜佳现有库存
     */
    @Override

    public List<FileMeiyijiaInventoryListVo> selectFileMeiyijiaInventoryList(FileMeiyijiaInventoryParam fileMeiyijiaInventoryParam) {

        // 对条码做特殊符号转换
        if (StringUtils.isNotBlank(fileMeiyijiaInventoryParam.getBarCode())) {
            fileMeiyijiaInventoryParam.setBarCode(com.ruoyi.common.utils.StringUtils.escapeLike(fileMeiyijiaInventoryParam.getBarCode()));
        }
        // 对条码做特殊符号转换
        if (StringUtils.isNotBlank(fileMeiyijiaInventoryParam.getCode())) {
            fileMeiyijiaInventoryParam.setCode(com.ruoyi.common.utils.StringUtils.escapeLike(fileMeiyijiaInventoryParam.getCode()));
        }

        List<FileMeiyijiaInventoryListVo> list = fileMeiyijiaInventoryMapper.selectFileMeiyijiaInventoryList(fileMeiyijiaInventoryParam);

        if(list.size()<1){
            return new ArrayList<>();
        }
        for (FileMeiyijiaInventoryListVo item:
        list) {
            item.setProfitMargin(item.getProfitMargin()+"%");
        }

        return list;
    }

    @Override

    public FileMeiyijiaInventoryListSumVo selectFileMeiyijiaInventoryMap(FileMeiyijiaInventoryParam fileMeiyijiaInventoryParam) {
        // 对条码做特殊符号转换
        if (StringUtils.isNotBlank(fileMeiyijiaInventoryParam.getType())) {
            fileMeiyijiaInventoryParam.setType(com.ruoyi.common.utils.StringUtils.escapeLike(fileMeiyijiaInventoryParam.getType()));
        }

        //List<FileMeiyijiaInventory> list = fileMeiyijiaInventoryMapper.selectList(fileMeiyijiaInventoryParam);
        //
        //if(list.size()<1){
        //    return result;
        //}
        
        ///**
        // * 转换数据格式
        // */
        //BigDecimal countSum = new BigDecimal("0");
        //BigDecimal retailPriveSum = new BigDecimal("0");
        //BigDecimal wholesalePriceSum = new BigDecimal("0");
        //for (FileMeiyijiaInventory item:
        //list) {
        //    BigDecimal count = new BigDecimal(item.getCount());
        //    BigDecimal retailPrive = new BigDecimal(item.getRetailPrive());
        //    BigDecimal wholesalePrice = new BigDecimal(item.getWholesalePrice());
        //    // 总库存
        //    countSum = countSum.add(count);
        //    // 总库存
        //    retailPriveSum = retailPriveSum.add(count.multiply(retailPrive));
        //    // 总库存
        //    wholesalePriceSum = wholesalePriceSum.add(count.multiply(wholesalePrice));
        //}
        //result.put("总库存数",countSum.setScale(0));
        //result.put("批发总金额",retailPriveSum.setScale(2,BigDecimal.ROUND_HALF_UP));
        //result.put("零售价金额",wholesalePriceSum.setScale(2,BigDecimal.ROUND_HALF_UP));
        FileMeiyijiaInventoryListSumVo result =new FileMeiyijiaInventoryListSumVo();

        FileMeiyijiaInventoryListSumVo selectCountSum = fileMeiyijiaInventoryMapper.selectCountSum(fileMeiyijiaInventoryParam);
        FileMeiyijiaInventoryListSumVo selectRetailPriveSum  = fileMeiyijiaInventoryMapper.selectRetailPriveSum(fileMeiyijiaInventoryParam);
        FileMeiyijiaInventoryListSumVo selectWholesalePriceSum = fileMeiyijiaInventoryMapper.selectWholesalePriceSum(fileMeiyijiaInventoryParam);
        result.setCountSum(selectCountSum!=null?selectCountSum.getCountSum():"0");
        result.setRetailPriveSum(selectRetailPriveSum!=null?selectRetailPriveSum.getRetailPriveSum():"0");
        result.setWholesalePriceSum(selectWholesalePriceSum!=null?selectWholesalePriceSum.getWholesalePriceSum():"0");



        return  result;
    }

    /**
     * 查询类型
     */
    @Override
    public List<DictTreeVo> getType() {
        List<DictTreeVo> result = new ArrayList<>();
        List<FileMeiyijiaInventory> allist = fileMeiyijiaInventoryMapper.selectTypeTree();
        if (allist.size() < 1) {
            return result;
        }

        Map<String, List<FileMeiyijiaInventory>> map = allist.stream().collect(Collectors.groupingBy(FileMeiyijiaInventory::getBigType));

        for (String item : map.keySet()) {
            DictTreeVo dictTreeVo = new DictTreeVo();
            dictTreeVo.setKey(item);
            dictTreeVo.setValue(item);
            dictTreeVo.setChild(map.get(item).stream().map(obj -> {
                DictTreeVo dict = new DictTreeVo();
                dict.setKey(obj.getType());
                dict.setValue(obj.getType());
                return dict;
            }).collect(Collectors.toList()));
            result.add(dictTreeVo);
        }

        return result;
    }
    
    public List<String> getids() {
        List<FileMeiyijiaInventory> allist = fileMeiyijiaInventoryMapper.selectIds();
        if (allist.size() < 1) {
            return new ArrayList<>();
        }
        return allist.stream().map(FileMeiyijiaInventory::getId).collect(Collectors.toList());
    }

}